/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing.jee.web.view;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.DateField;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import testing.jee.ejb.RequestBean;
import testing.jee.entity.Timeline;
import testing.jee.entity.Workday;
import testing.jee.entity.Workpackage;
import testing.jee.util.DateUtils;
import testing.jee.web.View;

/**
 *
 * @author nova
 */
@Component
@Scope(value = "session")
public class WeekView extends VerticalLayout implements View {

    @Autowired
    RequestBean req;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    DateField startSelector = new DateField("Show week of:");
    //DateField endSelector = new DateField("To:");
    private Date startDate;
    private Date endDate;
    VerticalLayout dateLayout = new VerticalLayout();
    HorizontalLayout overviewLayout = new HorizontalLayout();
    private final float TIMELINE_WIDTH = 160;

    @PostConstruct
    public void init() {
        HorizontalLayout dateChooserLayout = new HorizontalLayout();
        startSelector.setDateFormat("dd.MM.yyyy");
        startSelector.setShowISOWeekNumbers(false);
        startSelector.setResolution(DateField.RESOLUTION_DAY);
        startSelector.setImmediate(true);
        startSelector.addListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                startDate = DateUtils.normalize((Date) event.getProperty().getValue(), Calendar.MONDAY);
                endDate = DateUtils.toEndOfWeek(startDate);
                if (startDate.before(endDate)) {
                    initTimeline();
                }
            }
        });
/*
        endSelector.setDateFormat("dd.MM.yyyy");
        endSelector.setShowISOWeekNumbers(false);
        endSelector.setResolution(DateField.RESOLUTION_DAY);
        endSelector.setImmediate(true);
        endSelector.addListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                endDate = DateUtils.normalize((Date) event.getProperty().getValue(), Calendar.FRIDAY);
                if (endDate.after(startDate)) {
                    initTimeline();
                }
            }
        });*/
        dateChooserLayout.addComponent(startSelector);
        //dateChooserLayout.addComponent(endSelector);
        addComponent(dateChooserLayout);


        Panel scrollPanel = new Panel();
        overviewLayout.addComponent(dateLayout);
        overviewLayout.setSpacing(true);
        overviewLayout.setHeight(160, UNITS_PIXELS);
        dateLayout.setSpacing(true);

        scrollPanel.setContent(overviewLayout);
        scrollPanel.setHeight(200, UNITS_PIXELS);
        addComponent(scrollPanel);
    }

    private void initTimeline() {
        overviewLayout.removeAllComponents();
        dateLayout.removeAllComponents();
        if (startDate == null) {
            startDate = DateUtils.normalize(new Date(), Calendar.MONDAY);
        }

        if (endDate == null) {
            endDate = DateUtils.toEndOfWeek(startDate);
        }

        ArrayList<Timeline> timelines = new ArrayList<Timeline>( req.getTimelines(startDate, endDate));
        Collections.sort(timelines, new Comparator<Timeline> () {

            @Override
            public int compare(Timeline o1, Timeline o2) {
                return o1.getUser().getId().compareTo(o2.getUser().getId());
            }
            
        });
        List<Date> dates;
        if (timelines.size() > 0) {
            Timeline firstTimeLine = timelines.iterator().next();
            dates = firstTimeLine.getDates();

            HorizontalLayout dateSpacer = new HorizontalLayout();
            dateSpacer.setHeight("20px");
            dateLayout.addComponent(dateSpacer);
            for (Date d : dates) {
                Label dateLabel = new Label(dateFormat.format(d));
                dateLabel.setHeight("20px");
                dateLabel.setStyleName("rp-overview-name");
                dateLayout.addComponent(dateLabel);

            }
            overviewLayout.addComponent(dateLayout);
            for (Timeline t : timelines) {
                Label userNameLabel = new Label(t.getUser().getId());
                userNameLabel.setStyleName("rp-overview-name");
                userNameLabel.setWidth("100%");
                userNameLabel.setHeight("20px");

                VerticalLayout weeksLayout = new VerticalLayout();
                weeksLayout.setSpacing(true);
                weeksLayout.addComponent(userNameLabel);
                weeksLayout.setComponentAlignment(userNameLabel, Alignment.MIDDLE_CENTER);
                for (Date d : dates) {
                    Workday day = t.getWorkday(d);
                    HorizontalLayout dayLayout = new HorizontalLayout();
                    dayLayout.setWidth(TIMELINE_WIDTH, UNITS_PIXELS);
                    dayLayout.setHeight("20px");
                    dayLayout.setStyleName("rp-overview-day-free");
                    Iterator<Workpackage> it = day.getWorkpackages().iterator();
//                    int durationLeft = (int)TIMELINE_WIDTH;
                    Label dayLabel = new Label();
                    dayLabel.setWidth((8-day.getHoursLeft())*TIMELINE_WIDTH*0.125f, UNITS_PIXELS);
                    dayLabel.setStyleName("rp-overview-day-full");
                    StringBuilder label = new StringBuilder();
                    while (it.hasNext()) {
                        Workpackage wp = it.next();
                        label.append(wp.getLabel());
                        if (it.hasNext())
                            label.append(", ");
                    }
                    dayLabel.setCaption(label.toString());
                    dayLabel.setDescription(label.toString());
                    dayLayout.addComponent(dayLabel);
                    Label afterDaySpacer = new Label();
                    afterDaySpacer.setWidth(day.getHoursLeft()*TIMELINE_WIDTH*0.125f, UNITS_PIXELS);
                    afterDaySpacer.addStyleName("rp-overview-day-free");
                    dayLayout.addComponent(afterDaySpacer);
                    weeksLayout.addComponent(dayLayout);
                }
                overviewLayout.addComponent(weeksLayout);
            }
        }
    }

    @Override
    public void preView() {
        initTimeline();
    }

    @Override
    public void postView() {
    }
}
